<?php

namespace common\components;

use backend\modules\home\models\Category;
use backend\modules\home\models\Article;
use backend\modules\home\models\Config;
use backend\modules\home\models\Link;

class Tools
{

	public static function getTopmenu(){
        $list = Category::find()->where([
            'is_top_show' => 1, 
            'cid' => 0
        ])
        ->orderBy([
            'sort' => SORT_DESC,
            'id' => SORT_ASC
        ])
        ->select('id,title,code,icon')
        ->asArray()->all();
        return $list;
    }

    public static function getCateArticle($cid){
        $list = Article::find()->where([
            'cid' => $cid,
            'type' => 1,
            'status' => 1,
        ])
        ->orderBy([
            'order' => SORT_DESC,
            'id' => SORT_DESC,
        ])
        ->limit(5)
        ->asArray()
        ->all();
        
        return $list;
    }

    public static function getValue($key){
        $model = new Config();
        $res = $model->find()->where(['key' => $key])->asArray()->one();
        if($res){
            return $res['value'];
        }else{
            return array(
                'title' => '',
                'value' => '',
                'remark' => '',
                'key' => '',
            );
        }
    }

    public function getLinkList(){
	    return $list = Link::find()->orderBy([
            'sort' => SORT_DESC,
            'id' => SORT_ASC,
        ])->asArray()->all();
    }


    public static function getIp() {
        //strcasecmp 比较两个字符，不区分大小写。返回0，>0，<0。
        if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        $res =  preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
        return $res;

    }
}